import { addDialog } from "@/components/ReDialog";
import { useRouterNavigation } from "@/router/utils";
import { message } from "@/utils/message";
import type { PaginationProps } from "@pureadmin/table";
import { deviceDetection, getKeyList } from "@pureadmin/utils";
import dayjs from "dayjs";
import { type Ref, computed, h, onMounted, reactive, ref, toRaw } from "vue";
import ChooseAchiev from "../form/chooseAchiev.vue";
import editForm from "../form/index.vue";

// api
import { getResearchList } from "@/api/other/researchTeam"; // 科研团队
import {
  addAchiev,
  changeAchiev,
  delAchiev,
  getAchievList,
  upAchiev
} from "@/api/research/achiev";
import { getAchievTransList } from "@/api/research/achievTrans";
import { getOtherAwardList } from "@/api/research/award"; // 科研获奖
import { getPaperList } from "@/api/research/paper"; // 论文
import { getPatentList } from "@/api/research/patent"; // 专利
import { getProjectList } from "@/api/research/project"; // 横向、纵向项目
import { getUserList } from "@/api/system/user";
import { exportData, getTableCol } from "@/utils/common";
import {
  checkStatusRend,
  dataStatusRend,
  rejectDescRend,
  tableFileRend
} from "@/utils/table";
import { useRoute } from "vue-router";

export function useUser(tableRef: Ref) {
  const form = reactive({
    researchTeamId: "",
    masterUserId: "",
    examineStatus: "",
    status: "",
    keywords: "",
    subject: "",
    domain: "",
    orderBy: "desc",
    pageNum: 1,
    pageSize: 10
  });
  const formRef = ref();
  const dataList = ref([]);
  const allUserList = ref([]);
  const loading = ref(true);
  const tableCol = ref<any>({});
  const treeData = ref([]);
  const selectedNum = ref(0);
  const selectOpt = ref({
    tdList: [],
    hxList: [],
    zxList: [],
    lwList: [],
    zlList: [],
    hjList: [],
    cgzhList: []
  });
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const columns: TableColumnList = [
    {
      label: "科研成果名称",
      prop: "scrAchievementsName",
      fixed: "left",
      minWidth: 200
    },
    {
      label: "审核状态",
      prop: "examineStatus",
      minWidth: 90,
      cellRenderer: checkStatusRend
    },
    {
      label: "状态",
      prop: "status",
      minWidth: 80,
      cellRenderer: dataStatusRend
    },
    {
      label: "驳回原因",
      prop: "examineDesc",
      minWidth: 120,
      cellRenderer: rejectDescRend
    },
    {
      label: "团队名称",
      prop: "teamName",
      minWidth: 100,
      formatter: ({ researchTeam }) => researchTeam?.teamName || "--"
    },
    {
      label: "负责人",
      prop: "masterUser",
      minWidth: 100,
      formatter: ({ researchTeam }) => researchTeam?.masterUser?.name || "--"
    },
    {
      label: "联系方式",
      prop: "masterUserPhone",
      minWidth: 110,
      formatter: ({ researchTeam }) => researchTeam?.masterUser?.phone || "--"
    },
    {
      label: "依托单位",
      prop: "relyOnUnit",
      minWidth: 100
    },
    {
      label: "所属学科",
      prop: "subject",
      minWidth: 100
    },
    {
      label: "所属领域",
      prop: "domain",
      minWidth: 100
    },
    {
      label: "关键词",
      prop: "keywords",
      minWidth: 100
    },
    {
      label: "合同附件",
      prop: "additionFiles",
      minWidth: 100,
      align: "center",
      cellRenderer: ({ row }) => tableFileRend(row, "additionFiles")
    },
    {
      label: "获得积分",
      prop: "score",
      minWidth: 100,
      formatter: row => getScoreTotal(row)
    },
    {
      label: "创建人",
      prop: "createUserName",
      minWidth: 100
    },
    {
      label: "创建时间",
      prop: "gmtCreate",
      minWidth: 140,
      formatter: ({ gmtCreate }) => dayjs(gmtCreate).format("YYYY-MM-DD HH:mm")
    },
    {
      label: "修改时间",
      prop: "gmtModified",
      minWidth: 140,
      formatter: ({ gmtModified }) =>
        dayjs(gmtModified).format("YYYY-MM-DD HH:mm")
    },
    {
      label: "操作",
      prop: "operation",
      fixed: "right",
      align: "left",
      width: 270,
      slot: "operation"
    }
  ];

  const buttonClass = computed(() => {
    return [
      "!h-[20px]",
      "reset-margin",
      "!text-gray-500",
      "dark:!text-white",
      "dark:hover:!text-primary"
    ];
  });

  const getScoreTotal = item => {
    let allProjectList = [
      ...item.longitudinalProjects,
      ...item.horizontalProjects,
      ...item.otherObtainRewards,
      ...item.papers,
      ...item.patents,
      ...item.transformations
    ];
    return allProjectList
      .map(v => v.score || 0)
      .reduce((prev, curr) => prev + curr, 0);
  };

  // 查看商品详情
  const { push } = useRouterNavigation();
  const showDetail = row => {
    push({
      path: "/research/achiev/detail",
      query: { id: row.id }
    });
  };

  const handleDelete = async row => {
    await delAchiev(row.id);
    message("删除成功", { type: "success" });
    onSearch();
  };

  function handleSizeChange(val: number) {
    console.log(`${val} items per page`);
    form.pageSize = val;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    console.log(`current page: ${val}`);
    form.pageNum = val;
    onSearch();
  }

  /** 批量删除 */
  function onbatchDel() {
    // 返回当前选中的行
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
    // 接下来根据实际业务，通过选中行的某项数据，比如下面的id，调用接口进行批量删除
    message(`已删除用户编号为 ${getKeyList(curSelected, "id")} 的数据`, {
      type: "success"
    });
    tableRef.value.getTableRef().clearSelection();
    onSearch();
  }

  async function onSearch() {
    loading.value = true;
    const { data } = await getAchievList(toRaw(form));
    dataList.value = data.records || [];
    pagination.total = data.total;
    pagination.pageSize = data.pageSize;
    pagination.currentPage = data.pageNum;

    setTimeout(() => {
      loading.value = false;
    }, 500);
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };

  // 导出数据
  const exportModuleData = () => {
    exportData("科研成果", "/scr/achievements/export", form);
  };

  function openDialog(title = "新增", row?) {
    let masterUser = "";
    if (row?.researchTeam) {
      masterUser = row.researchTeam.masterUser.name;
    }
    let keywordList = [
      {
        keywords: ""
      }
    ];
    if (row?.keywords) {
      keywordList = row.keywords.split(",").map(v => {
        return { keywords: v };
      });
    }
    addDialog({
      title: `${title}科研成果`,
      sureBtnLoading: true,
      props: {
        formInline: {
          id: row?.id ?? undefined,
          title,
          achievementSupport: row?.achievementSupport ?? "",
          additionFiles: row?.additionFiles ?? "",
          domain: row?.domain ?? "",
          keyPoints: row?.keyPoints ?? "",
          keywords: row?.keywords ?? "",
          keywordList: keywordList,
          overAchievements: row?.overAchievements ?? "",
          longitudinalProjectIds: row?.longitudinalProjects
            ? row.longitudinalProjects.map(v => v.id)
            : [],
          horizontalProjectIds: row?.horizontalProjects
            ? row.horizontalProjects.map(v => v.id)
            : [],
          otherObtainRewardIds: row?.otherObtainRewards
            ? row.otherObtainRewards.map(v => v.id)
            : [],
          achievementTransformationIds: row?.transformations
            ? row.transformations.map(v => v.id)
            : [],
          paperIds: row?.papers ? row.papers.map(v => v.id) : [],
          patentIds: row?.patents ? row.patents.map(v => v.id) : [],
          masterUser: masterUser,
          relyOnUnit: row?.relyOnUnit ?? "",
          researchTeamId: row?.researchTeamId ?? null,
          scrAchievementsName: row?.scrAchievementsName ?? "",
          subject: row?.subject ?? "",
          achievementsType: row?.achievementsType ?? ""
        },
        userList: allUserList.value || [],
        selectOpt: selectOpt.value || {}
      },
      width: "1000px",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef, formInline: null }),
      beforeSure: (done, { options, closeLoading }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline;
        function chores() {
          message("操作成功", {
            type: "success"
          });
          done(); // 关闭弹框
          onSearch(); // 刷新表格数据
        }
        FormRef.validate(async valid => {
          if (valid) {
            let newForm = { ...curData };
            if (newForm.keywordList && newForm.keywordList.length > 0) {
              newForm.keywords = newForm.keywordList
                .map(v => v.keywords)
                .join(",");
            }
            delete newForm.keywordList;
            console.log("newForm ", newForm);
            // 表单规则校验通过
            if (title === "新增") {
              await addAchiev(newForm);
              chores();
            } else {
              await upAchiev(newForm);
              chores();
            }
          }
          closeLoading();
        });
      }
    });
  }

  // 选择科研成果
  const chooseAchievRef = ref();
  function doChooseAchiev(row) {
    addDialog({
      title: "添加科研成果",
      sureBtnLoading: true,
      props: {
        formInline: {
          id: row?.id ?? undefined,
          achievementsType: row?.achievementsType ?? "",
          longitudinalProjectIds: [],
          horizontalProjectIds: [],
          otherObtainRewardIds: [],
          achievementTransformationIds: [],
          paperIds: [],
          patentIds: []
        },
        selectOpt: selectOpt.value || {}
      },
      width: "800px",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () =>
        h(ChooseAchiev, { ref: chooseAchievRef, formInline: null }),
      beforeSure: async done => {
        const curData = chooseAchievRef.value.getForm();
        function chores() {
          message("操作成功", {
            type: "success"
          });
          done(); // 关闭弹框
          onSearch(); // 刷新表格数据
        }

        console.log("curData ", curData);
        await changeAchiev(curData);
        chores();
      }
    });
  }

  const loadAllUser = async () => {
    let params = {
      pageNum: 1,
      pageSize: 500
    };
    let { data } = await getUserList(params);
    allUserList.value = data.records || [];
  };

  // 获取项目集合
  const loadListOpt = async () => {
    let params = {
      examineStatus: 1,
      orderBy: "desc",
      pageNum: 1,
      pageSize: 999
    };

    // 团队
    getResearchList(params).then(res => {
      selectOpt.value.tdList = res?.data?.records || [];
    });

    // 项目类型 1纵向 2横向
    getProjectList({ projectType: 2, ...params }).then(res => {
      selectOpt.value.hxList = res?.data?.records || [];
    });

    getProjectList({ projectType: 1, ...params }).then(res => {
      selectOpt.value.zxList = res?.data?.records || [];
    });

    getPaperList(params).then(res => {
      selectOpt.value.lwList = res?.data?.records || [];
    });

    getPatentList(params).then(res => {
      selectOpt.value.zlList = res?.data?.records || [];
    });

    getOtherAwardList(params).then(res => {
      selectOpt.value.hjList = res?.data?.records || [];
    });

    getAchievTransList(params).then(res => {
      selectOpt.value.cgzhList = res?.data?.records || [];
    });
  };

  onMounted(async () => {
    const { query } = useRoute();
    if (query.examineStatus) {
      form.examineStatus = Number(query.examineStatus) as any;
    }
    if (query.status) {
      form.status = Number(query.status) as any;
    }
    tableCol.value = await getTableCol("achiev");

    onSearch();

    // 获取所有用户
    loadAllUser();

    loadListOpt();
  });

  return {
    form,
    tableCol,
    loading,
    columns,
    dataList,
    treeData,
    selectedNum,
    pagination,
    buttonClass,
    deviceDetection,
    onSearch,
    resetForm,
    allUserList,
    selectOpt,
    onbatchDel,
    openDialog,
    doChooseAchiev,
    showDetail,
    handleDelete,
    handleSizeChange,
    handleCurrentChange,
    exportModuleData
  };
}
